package cn.minsh.lims.eoms.modules.job.task;

import cn.minsh.lims.eoms.modules.app.entity.MaintenancePlanEntity;
import cn.minsh.lims.eoms.modules.app.enums.BusiTypeEnum;
import cn.minsh.lims.eoms.modules.app.enums.PlanStatusEnum;
import cn.minsh.lims.eoms.modules.app.service.MaintenancePlanService;
import cn.minsh.lims.eoms.modules.app.utils.LocalDateUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * @author Administrator
 * 保养计划状态处理
 */
@Component("checkMaintenancePlanStatusTask")
public class CheckMaintenancePlanStatusTask implements ITask {

    @Autowired
    private MaintenancePlanService maintenancePlanService ;


    @Override
    public void run(String params) {

        List<Integer> statusList = new ArrayList<>() ;
        statusList.add(PlanStatusEnum.NOT_STARTED.getCode()) ;
        statusList.add(PlanStatusEnum.STARTED.getCode()) ;
        QueryWrapper<MaintenancePlanEntity> wrapper = new QueryWrapper<>() ;
        wrapper.eq("type", BusiTypeEnum.MAINTENANCEPLAN.getCode()) ;
        wrapper.in("status",statusList) ;
        List<MaintenancePlanEntity> list = maintenancePlanService.list(wrapper) ;

        if (!CollectionUtils.isEmpty(list)){
            List<MaintenancePlanEntity> updateList = new ArrayList<>() ;
            list.stream().forEach(e->{
                if (e.getInvalidTime()!=null){
                    if (new Date().after(e.getInvalidTime())){
                        //已结束
                        e.setStatus(PlanStatusEnum.STARTED.getCode());
                        updateList.add(e) ;
                        return;
                    }
                }
                //未开始
                if (PlanStatusEnum.NOT_STARTED.getCode().equals(e.getStatus())){
                    //判断时间是否到了开始/或者结束
                    if (new Date().after(e.getFirstPlanDate())){
                        //同一天，修改为进行中
                        e.setStatus(PlanStatusEnum.STARTED.getCode());
                        updateList.add(e) ;
                        return;
                    }
                }
            });
            if (!CollectionUtils.isEmpty(updateList)){
                maintenancePlanService.updateBatchById(updateList) ;
            }
        }
    }
}
